package jp.gr.java_conf.yuzu_project;

import jp.gr.java_conf.yuzu_project.common.CommonUtil;
import jp.gr.java_conf.yuzu_project.common.SaveDataStock;
import jp.gr.java_conf.yuzu_project.parts.QuickSaveLoadUtil;
import jp.gr.java_conf.yuzu_project.parts.StringDispSample;
import jp.gr.java_conf.yuzu_project.view.PlaySurfaceView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * プレイ画面.
 * 
 * @author ゆずプロジェクト
 * 
 */
public class PlayActivity extends Activity {

	/** 台詞表示用. */
	private TextView tx = null;
	/** 全画面レイアウト. */
	private LinearLayout layout;
	/** シングルタップ、ロングタップ用クラス */
	private GestureDetector serifTapListener;
	/** 文字送り用クラス. */
	private StringDispSample stringDisp;
	/** 文字・画像用フレームレイアウト */
	private FrameLayout serifLayout;
	/** セーブデータ保存用オブジェクト */
	private SaveDataStock saveData;
	/** ポップアップウィンドウ */
	private PopupWindow popupWindow;
	/** 現在章 */
	private String chapter;
	/** 背景、立ち絵表示用surfaceview */
	private PlaySurfaceView playSurfaceView;
	/** 背景、立ち絵表示用surfaceview */
	private SurfaceView surfaceView;
	/** クイックロードはい リスナー*/
	private View.OnClickListener loadYes = 
			new OnClickListener() {
				
				public void onClick(View v) {
					new QuickTask().execute(CommonUtil.LOAD_INTENT);
					if (popupWindow != null) {
						popupWindow.dismiss();
						popupWindow = null;
					}
				}
			};
	/** クイックロードいいえリスナー */
	private View.OnClickListener loadNo = 
			new OnClickListener() {
						
				public void onClick(View v) {
					if (popupWindow != null) {
						popupWindow.dismiss();
						popupWindow = null;
					}
				}
			};

	/** ダミーデータ */
	String[] wordBox = { "1234567890", "1234567890", "1234567890" };

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_play);

	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d("check", "before gsDt.onTouchEvent");
		boolean r = serifTapListener.onTouchEvent(event);
		Log.d("check", "r = " + r);
		return false;
	}

	/**
	 * UI生成用メソッド.
	 */
	private void reparation() {
		
		// セーブデータ
		saveData = (SaveDataStock) getIntent().getSerializableExtra(CommonUtil.SAVE_OBJ_INTENT_KEY);
		
		// 文字表示用テキストビュー
		tx = (TextView) findViewById(R.id.play_textView);
		tx.setTextColor(Color.WHITE);
		
		// FrameLayoutの非表示用
		serifLayout = (FrameLayout) findViewById(R.id.words_fream);
		
		// 画面サイズ
		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display disp = wm.getDefaultDisplay();
		
		// surfaceview
		surfaceView = (SurfaceView) findViewById(R.id.PlaySurfaceView);
		playSurfaceView = new PlaySurfaceView(getApplicationContext(), surfaceView, disp.getWidth(), disp.getHeight());
		
		// シングルタップ、ダブルタップ用リスナー
		serifTapListener = new GestureDetector(getApplicationContext(),new GestureDetector.SimpleOnGestureListener() {

			@Override
			// シングルタップ時に呼び出される処理
			public boolean onSingleTapConfirmed(MotionEvent e) {
				Log.d("check", "onSingleTapConfirmed");
				Toast.makeText(getApplicationContext(), "シングルタップ",
						Toast.LENGTH_SHORT).show();

				// 台詞枠が非表示(View.INVISIBLE)の場合、台詞枠表示
				if (serifLayout.getVisibility() == View.INVISIBLE) {
					serifLayout.setVisibility(View.VISIBLE);
				}
				playSurfaceView.chageBackGround(0);
				return false;
			}

			@Override
			// ロングタップ時に呼び出される処理
			public void onLongPress(MotionEvent e) {
				Toast.makeText(getApplicationContext(), "ロングタップ",
						Toast.LENGTH_SHORT).show();

				// 台詞枠が表示状態(View.VISIBLE)の場合、台詞枠非表示
				if (serifLayout.getVisibility() == View.VISIBLE) {
					serifLayout.setVisibility(View.INVISIBLE);
				}

			}
		});

		stringDisp = new StringDispSample(wordBox, 0, tx, serifLayout);
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		tx = null;
		layout = null;
		serifTapListener = null;
		stringDisp = null;
		serifLayout = null;

		super.onPause();
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		reparation();
		super.onResume();
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, CommonUtil.MENU_ID_1, Menu.NONE, CommonUtil.MENU_TITLE_1);
		menu.add(Menu.NONE, CommonUtil.MENU_ID_2, Menu.NONE, CommonUtil.MENU_TITLE_2);
		menu.add(Menu.NONE, CommonUtil.MENU_ID_3, Menu.NONE, CommonUtil.MENU_TITLE_3);
		menu.add(Menu.NONE, CommonUtil.MENU_ID_4, Menu.NONE, CommonUtil.MENU_TITLE_4);
		menu.add(Menu.NONE, CommonUtil.MENU_ID_5, Menu.NONE, CommonUtil.MENU_TITLE_5);
		return super.onCreateOptionsMenu(menu);
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent intentSave = new Intent(PlayActivity.this, SaveActivity.class);
		switch(item.getItemId()) {
		case CommonUtil.MENU_ID_1:
			// セーブ
			intentSave.putExtra(CommonUtil.SAVE_LOAD_INTENT_KEY, CommonUtil.SAVE_INTENT);
			intentSave.putExtra(CommonUtil.SAVE_OBJ_INTENT_KEY, saveData);
			intentSave.putExtra(CommonUtil.CHAPTER_KEY, chapter);
			startActivityForResult(intentSave, CommonUtil.INTENT_CODE);
			break;
		case CommonUtil.MENU_ID_2:
			// ロード
			intentSave.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentSave.putExtra(CommonUtil.SAVE_LOAD_INTENT_KEY, CommonUtil.LOAD_INTENT);
			startActivityForResult(intentSave, CommonUtil.INTENT_CODE);
			break;
		case CommonUtil.MENU_ID_3:
			// クイックセーブ
			if (saveData != null) {
				new QuickTask().execute(CommonUtil.SAVE_INTENT);				
			} else {
				toastDisp(getString(R.string.quick_save_no_data_title), getString(R.string.quick_save_no_data_message));
			}
			break;
		case CommonUtil.MENU_ID_4:
			// クイックロード
			popupDisp(loadYes, loadNo, getString(R.string.quick_load_check_message));
			break;
		case CommonUtil.MENU_ID_5:
			// 設定
			Intent settingIntent = new Intent(PlayActivity.this, OptionActiviy.class);
			startActivityForResult(settingIntent, CommonUtil.INTENT_BACK);
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}
	
	/**
	 * クイックセーブ・ロード用タスク
	 * @author ゆずプロジェクト
	 *
	 */
	private class QuickTask extends AsyncTask<String, Integer, Long> {
		
		private ProgressBar progress;
		private TextView textView;
		
		@Override
		protected void onPreExecute() {
			progress = (ProgressBar) findViewById(R.id.load_progress);
			progress.setVisibility(View.VISIBLE);
			textView = (TextView) findViewById(R.id.lode_message);
			textView.setText(getString(R.string.under_processing));
			super.onPreExecute();
		}
		
		@Override
		protected Long doInBackground(String... params) {
			
			QuickSaveLoadUtil qslu = new QuickSaveLoadUtil(getApplicationContext());
			Long result = -1L;
			
			if (params[0].equals(CommonUtil.SAVE_INTENT)) {
				// セーブ
				boolean save = qslu.quickSave(saveData);
				if (save) {
					// 成功
					result = 1L;
				} else {
					// 失敗
					result = 0L;
				}
			} else {
				// ロード
				saveData = qslu.quickLoad();
				result = 2L;
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(Long result) {
			progress.setVisibility(View.GONE);
			textView.setVisibility(View.GONE);
			if (progress != null) {
				progress = null;
			}
			if (textView != null) {
				textView = null;
			}
			
			if (result == 1L) {
				toastDisp(getString(R.string.quick_save_success_title), getString(R.string.quick_save_success_message));
			} else if (result == 0L) {
				toastDisp(getString(R.string.quick_save_failure_title), getString(R.string.quick_save_failure_message));
			} else if (result == 2L) {
				Intent intent = new Intent(PlayActivity.this, PlayActivity.class);
				intent.putExtra(CommonUtil.SAVE_OBJ_INTENT_KEY, saveData);
				startActivity(intent);
				finish();
			}
			
			super.onPostExecute(result);
		}
		
	}
	
	/**
	 * カスタムトースト表示
	 * @param title タイトル
	 * @param message メッセージ
	 */
	private void toastDisp(String title, String message) {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.save_activity_error_message, null);
		TextView txTitle = (TextView) layout.findViewById(R.id.save_error_title);
		txTitle.setText(title);
		TextView txMessage = (TextView) layout.findViewById(R.id.save_error_message);
		txMessage.setText(message);
		Toast toast = new Toast(getApplicationContext());
		toast.setView(layout);
		toast.show();
	}
	
	/**
	 * ウィンドウポップアップ表示
	 * @param yesListener 「はい」ボタン
	 * @param noListener 「いいえ」ボタン
	 * @param message 表示メッセージ
	 */
	private void popupDisp(View.OnClickListener yesListener, View.OnClickListener noListener, String message) {
		LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View popupView = (View)inflater.inflate(R.layout.window_popup_yes_no, null);
		popupView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
		View view = findViewById(R.id.play_activity_top);
		popupWindow = new PopupWindow(view);
		popupWindow.setContentView(popupView);
		popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.showAsDropDown(view, 300, -500);
		TextView text = (TextView) popupWindow.getContentView().findViewById(R.id.window_popup_message);
		text.setText(message);
		Button yesButton = (Button) popupWindow.getContentView().findViewById(R.id.popup_yes_button);
		yesButton.setOnClickListener(yesListener);
		Button noButton = (Button) popupWindow.getContentView().findViewById(R.id.popup_no_button);
		noButton.setOnClickListener(noListener);
	}
}
